package com.photoeditor.demo.model.face.report.reportlogic;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.airbnb.lottie.LottieAnimationView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.common.base.ComponentContext;
import com.common.base.log.DLog;
import com.common.base.utils.DeviceUtils;
import com.common.base.utils.thread.ThreadPool;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.photoeditor.R;
import com.photoeditor.demo.app.ItemClickSupport;
import com.photoeditor.demo.model.event.GotoAdVideoPageEvent;
import com.photoeditor.demo.model.event.GotoSubscribePageEvent;
import com.photoeditor.demo.model.image.util.ImageHelper;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.subscribe.manager.AppVipManager;
import com.photoeditor.demo.model.bean.face.FaceDetectBeanV4;
import com.photoeditor.demo.model.bean.face.ScanInfo;
import com.photoeditor.demo.model.subscribe.strategy.OneFreeStrategyManager;
import com.photoeditor.demo.model.subscribe.strategy.RateNewStrategyBean;
import com.photoeditor.demo.ui.activity.face.FaceLogicActivity;
import com.photoeditor.demo.ui.adapter.face.FaceTemplateAdapter;
import com.photoeditor.demo.model.bean.SwapItemBean;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.util.AsyncTask;
import com.photoeditor.demo.util.BitmapUtils;
import com.photoeditor.demo.util.BlurUtil;
import com.photoeditor.demo.util.FastBlur;
import com.photoeditor.demo.util.TimeConstant;
import com.photoeditor.demo.util.ToastUtil;
import com.photoeditor.demo.util.Utils;
import com.photoeditor.demo.util.face.FaceBaseCallback;
import com.photoeditor.demo.util.face.FaceUtil;
import com.photoeditor.demo.util.transformation.BlurTransformation;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;

import static com.photoeditor.demo.model.bean.face.BaseFaceResultBean.REPORT_TYPE_EXOTIC;
import static com.photoeditor.demo.model.subscribe.strategy.OneFreeStrategyManager.ADVANCE_OBTAIN_RESULT;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_ASIAN;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_BLACK;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_CAUCASIAN;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_HISIPANIC;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_MIDDLEEASTERN;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_OTHER;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_10;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_4;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_6;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_ABOVE_10;

/**
 * Created by @author winn on 2018/10/30.
 */

public class ExoticReportLogic extends BaseReportLogic {
    private FaceDetectBeanV4 mResultBean;
    private ScanInfo mScanInfo;

    private FaceTemplateAdapter mAdapter;
    private RecyclerView mTemplateListView;
    private ImageView mImageView;
    LottieAnimationView mLoadingView;

    private boolean mIsLoading;
    private List<Integer> arrayList = new ArrayList<>();
    private List<SwapItemBean> mSwapItemBeanList = new ArrayList<>();
    private String mTemplateId;
    private final String TAG = "testLog";
    private String mImagePath;
    /**
     * 当网络请求合并变脸之后，需要根据模板做缓存
     * key：模板id
     * value：接口返回的图片的base64
     */
    private Map<String, String> mSwapCache = new HashMap<>();
    private String mCompressPic;
    private Activity mActivity;
    private Bitmap mOriBitmap;
    private RelativeLayout mBgLayout;
    private Bitmap mBackgroundBitmap;
    private Bitmap mBluredBitmap;
    private int margin;

    private int mImageViewWidth, mImageViewHeight;

    public ExoticReportLogic(FaceDetectBeanV4 bean, ScanInfo scanInfo) {
        super(REPORT_TYPE_EXOTIC);
        mResultBean = bean;
        mScanInfo = scanInfo;
    }

    public void setActivity(Activity activity) {
        mActivity = activity;
    }

    @Override
    public View getReportView(ViewGroup parent) {
        ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.report_exotic, parent, false);
        mContentView = viewGroup;
        mTemplateListView = viewGroup.findViewById(R.id.rv_template_list);
        mImageView = viewGroup.findViewById(R.id.effect_img);
        mLoadingView = viewGroup.findViewById(R.id.loading_animation_view);
        mBgLayout = viewGroup.findViewById(R.id.pic_container);

        margin = DeviceUtils.dip2px(26);

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mImageView.getLayoutParams();
        mImageViewWidth = DeviceUtils.getScreenWidthPx() - margin;
        mImageViewHeight = DeviceUtils.getScreenWidthPx() - margin;
        layoutParams.height = mImageViewHeight;
        layoutParams.width = mImageViewWidth;
        mImageView.setLayoutParams(layoutParams);

        if (mScanInfo.getImgList() != null && mScanInfo.getImgList().size() > 0) {
            mImagePath = mScanInfo.getImgList().get(0);
            mOriBitmap = BitmapFactory.decodeFile(mScanInfo.getImgList().get(0));
            mImageView.setImageBitmap(mOriBitmap);
        }

        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                initData();
            }
        }, 1000);
        createBackgroundBitmap(mOriBitmap);
        mBgLayout.setBackground(new BitmapDrawable(mBackgroundBitmap));

        return viewGroup;
    }

    private void initData() {
        mAdapter = new FaceTemplateAdapter();
        ItemClickSupport itemClickSupport = new ItemClickSupport(mTemplateListView, mAdapter, new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View view, int position, long itemId) {
                if (isLoading()) {//如果当前接口请求中，点击切换下一个，不响应
                    return;
                }
                if (position != getLastPosition()) {
                    //保存被点击位置
                    saveSelectPosition(position);
                    mAdapter.setSelectedPosition(position);
                    //需要获取图像图片的base64字符串 -》接口
                    DLog.i("testLog", "onItemClick: compressAndRequest");
                    if (position != 0) {
                        mTemplateId = mSwapItemBeanList.get(position).getTemplateId();
                        OneTimeVipHelper.getInstance().setTemplateId(mTemplateId);
                        //统计
                        templateClickStat(mTemplateId);
                        if (AppVipManager.isVip() || OneTimeVipHelper.getInstance().isTemplateUnlocked(mTemplateId)) {
                            if (mMaskLayout != null) {
                                mMaskLayout.setVisibility(View.GONE);
                            }
                            compressAndRequest(mTemplateId);
                        } else {
                            //非vip用户弹出遮罩
                            if (mMaskLayout != null) {
                                mMaskLayout.setVisibility(View.VISIBLE);
                                Glide.with(mActivity)
                                        .asBitmap()
                                        .load(mSwapItemBeanList.get(position).getUrl())
                                        .into(new SimpleTarget<Bitmap>() {
                                            @Override
                                            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                                mMaskLayout.setBackground(null);
                                                mBluredBitmap = BlurUtil.blur2(ComponentContext.getContext(), resource, 10, 1);
                                                mImageView.setImageBitmap(mBluredBitmap);
                                                createMaskBgBitmap();
                                            }
                                        });
                                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING);
                                return;
                            }
                            ViewStub maskStub = (ViewStub)mContentView.findViewById(R.id.stub_subscribe_mask);
                            mMaskLayout = maskStub.inflate();
                            Glide.with(mActivity)
                                    .asBitmap()
                                    .load(mSwapItemBeanList.get(position).getUrl())
                                    .into(new SimpleTarget<Bitmap>() {
                                        @Override
                                        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                            mMaskLayout.setBackground(null);
                                            mBluredBitmap = BlurUtil.blur2(ComponentContext.getContext(), resource, 10, 1);
                                            mImageView.setImageBitmap(mBluredBitmap);
                                            createMaskBgBitmap();
                                        }
                                    });
                            //策略平台控制，0——旧样式，1——AD弹框，2——评分引导一天免费弹框
                            RateNewStrategyBean.RateNewStrategyBeanConfig beanConfig = OneFreeStrategyManager.getOneFreeVipOrAdStrategyConfig();;
                            if (beanConfig == null || beanConfig.getRateType() != ADVANCE_OBTAIN_RESULT || SPDataManager.isFirstInAdvanceResultPage()) {
                                //模糊页不展示watch video按钮
                                RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams)mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
                                lps.bottomMargin = DeviceUtils.dip2px(24);
                                mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
                                mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.GONE);
                            }
                            mMaskLayout.findViewById(R.id.rl_continue_vip).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    //跳转到订阅页面
                                    EventBus.getDefault().post(new GotoSubscribePageEvent());
                                }
                            });
                            mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    //跳转到激励视频
                                    EventBus.getDefault().post(new GotoAdVideoPageEvent());
                                }
                            });
                        }
                    } else {
                        OneTimeVipHelper.getInstance().setTemplateId(OneTimeVipHelper.original);
                        mImageView.setImageBitmap(mOriBitmap);
                        if (mMaskLayout != null) {
                            mMaskLayout.setVisibility(View.GONE);
                        }
                    }
                }
            }
        });
        mAdapter.setItemClickSupport(itemClickSupport);
        requestTemplates();
        mAdapter.setData(mSwapItemBeanList);
        mTemplateListView.setLayoutManager(new LinearLayoutManager(ComponentContext.getContext(), LinearLayoutManager.HORIZONTAL, false));
        mTemplateListView.setAdapter(mAdapter);
        mTemplateListView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.right = DeviceUtils.dip2px(16);
            }
        });
        if (!TextUtils.isEmpty(OneTimeVipHelper.getInstance().getLatestUnlockedTid())) {
            //直接发起请求融合
            mergeTemplate(OneTimeVipHelper.getInstance().getLatestUnlockedTid());
        }
    }

    private void createMaskBgBitmap() {
        View activityView = mBgLayout;
        activityView.setDrawingCacheEnabled(true);
        activityView.destroyDrawingCache();
        activityView.buildDrawingCache();
        Bitmap bmp = activityView.getDrawingCache();
        Bitmap copy = bmp.copy(Bitmap.Config.ARGB_8888, true);
        BlurUtil.blur(mActivity, copy, 10);
        mMaskLayout.setBackground(new BitmapDrawable(copy));
        activityView.destroyDrawingCache();
        activityView.setDrawingCacheEnabled(false);
    }

    public void mergeTemplate(String templateId) {
        mTemplateId = templateId;
        if (mMaskLayout != null) {
            mMaskLayout.setVisibility(View.GONE);
        }
        compressAndRequest(mTemplateId);
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                if (mAdapter != null) {
                    List<SwapItemBean> itemBeans = mAdapter.getData();
                    int i = 0;
                    if (itemBeans != null && !itemBeans.isEmpty()) {
                        for (SwapItemBean bean: itemBeans) {
                            if (TextUtils.equals(mTemplateId, bean.getTemplateId())) {
                                break;
                            }
                            i++;
                        }
                        mAdapter.setSelectedPosition(i);
                    }
                }
            }
        }, 1000);
    }

    //生成背景
    private void createBackgroundBitmap(Bitmap srcBitmap) {
        int scaleRatio = 5;
        if (srcBitmap == null || srcBitmap.isRecycled()) {
            return;
        }
        Bitmap blurBitmap = srcBitmap.createScaledBitmap(srcBitmap,
                srcBitmap.getWidth() / scaleRatio,
                srcBitmap.getHeight() / scaleRatio,
                false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            blurBitmap = BlurTransformation.blur(ComponentContext.getContext(), blurBitmap, 25);
        } else {
            blurBitmap = FastBlur.doBlur(blurBitmap, 25, true);
        }

        Paint bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        //background
        mBackgroundBitmap = Bitmap.createBitmap(blurBitmap.getWidth(), blurBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas1 = new Canvas(mBackgroundBitmap);
        bitmapPaint.setAlpha(30);
        canvas1.drawBitmap(blurBitmap, 0, 0, bitmapPaint);
    }

    private void startRequest() {
        mIsLoading = true;
    }

    private void stopRequest() {
        mIsLoading = false;
    }

    public boolean isLoading() {
        return mIsLoading;
    }

    private int removeLastPosition() {
        if (arrayList.size() > 0) {
            arrayList.remove(arrayList.size() - 1);
        }
        return -1;
    }

    private void saveSelectPosition(int position) {
        arrayList.add(position);
    }

    private int getLastPosition() {
        int index = arrayList.size() - 1;
        if (index < 0) {
            return -1;
        }
        return arrayList.get(index);
    }

    private void tryGetTemplatesAgain() {
        if (mActivity == null) {
            return;
        }
        FaceUtil.showExitDialog(mActivity,
                mActivity.getResources().getString(R.string.net_connect_error),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mActivity.onBackPressed();
                    }
                },
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        compressAndRequest(mTemplateId);
                    }
                },
                new FaceUtil.ExitDialogListener() {
                    @Override
                    public void onExitDialogShow() {

                    }
                }
        );
    }

    private void requestTemplates() {
        FaceUtil.getFaceTemplates(this, new FaceBaseCallback(){
            @Override
            public void onSuccess(Response response) {
                super.onSuccess(response);
                okhttp3.Response rawResponse = response.getRawResponse();
                if (rawResponse != null) {
                    ResponseBody body = rawResponse.body();
                    if (body != null) {
                        try {
                            FaceUtil.parseFaceTemplateBean(body.string(), mSwapItemBeanList, "");
                            if (!mSwapItemBeanList.isEmpty()) {
                                //增加一个Original
                                SwapItemBean oriBean = new SwapItemBean();
                                oriBean.setOriginal(true);
                                oriBean.setUrl(mImagePath);
                                oriBean.setName(mActivity.getResources().getString(R.string.original));
                                mSwapItemBeanList.add(0, oriBean);
                                mAdapter.setData(mSwapItemBeanList);
                                mAdapter.setSelectedPosition(0);
                                return;
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                tryGetTemplatesAgain();
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
                tryGetTemplatesAgain();
            }
        });
    }

    /**
     * 点击模板的时候，统计
     *
     * @param templateId 具体模板id
     */
    private void templateClickStat(String templateId) {
//        StatisticsUtils.statisicsCustomFunction(
//                StatisticsConstant.UMENG_CUSTOM_EVENT_EDITOR,
//                StatisticsConstant.UMENG_CUSTOM_KEY_FUNCTION,
//                StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_MAINPAGE +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        StatisticsConstant.MAIN_BTN_SWAP +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        StatisticsConstant.FACE_SWAP_TEMPLATE_CLICK +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        templateId
//        );
    }

    /**
     * 换脸接口的，每次请求stat
     */
    private void requestStartStat() {
//        StatisticsUtils.statisicsCustomFunction(UMENG_CUSTOM_EVENT_EDITOR, UMENG_CUSTOM_KEY_FUNCTION,
//                StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_MAINPAGE +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        StatisticsConstant.MAIN_BTN_SWAP +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        StatisticsConstant.FACE_SWAP_REQUEST
//        );
    }

    /**
     * 换脸接口成功，统计耗时区间
     *
     * @param second 耗时区间
     */
    private void requestSucceedStat(String second) {
//        StatisticsUtils.statisicsCustomFunction(UMENG_CUSTOM_EVENT_EDITOR, UMENG_CUSTOM_KEY_FUNCTION,
//                StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_MAINPAGE +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        StatisticsConstant.MAIN_BTN_SWAP +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        StatisticsConstant.FACE_SWAP_REQUEST_SUCCESS +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        second
//        );
    }

    /**
     * 获取接口请求的耗时区间
     *
     * @param startRequest 开始请求时间
     * @return 区间文本
     */
    private String getTimeInterval(long startRequest) {
        long successRequest = System.currentTimeMillis();
        long diff = successRequest - startRequest;
        float second = diff / 1000f;
        String secondText = "";
        if (second < 4) {
            secondText = "[0.4)";
        } else if (second >= 4 && second < 6) {
            secondText = "[4.6)";
        } else if (second >= 6 && second < 10) {
            secondText = "[6.10)";
        } else if (second >= 10) {
            secondText = "[10.)";
        }
        return secondText;
    }

    /**
     * 压缩图片，请求接口
     *
     * @param templateId id
     */
    private void compressAndRequest(final String templateId) {
        DLog.i("testLog", "选择模板id：" + templateId);
        if (mSwapCache.containsKey(templateId)) {
            //有缓存
            String picBase64 = mSwapCache.get(templateId);
            //转byte[] 转交给glide处理
            DLog.i(TAG, "compressAndRequest: 直接使用缓存");
            showSwapPic(picBase64);
            return;
        }
        showLoading();
        ThreadPool.runOnNonUIThread(new Runnable() {
            @Override
            public void run() {
                //增加压缩缓存，因为原图和模板合并，原图pic是固定，只需要压缩一次，就可以，下次请求可以复用
                if (!TextUtils.isEmpty(mCompressPic)) {
                    requestSwap(templateId, mCompressPic);
                    return;
                }
                //
                Bitmap bitmap = ImageHelper.getBitmapFromPath(mImagePath);
                //压缩图片
                bitmap = ImageHelper.compressJpgToLimitKB(bitmap, 100);
                try {
                    mCompressPic = ImageHelper.bitmapToBase64(bitmap);
                    DLog.i(TAG, "onSuccess: compressImage");
                    requestSwap(templateId, mCompressPic);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private long startRequest;
    private void requestSwap(final String templateId, String pic) {
        DLog.e(TAG, "requestSwap");
        startRequest = System.currentTimeMillis();
        requestStartStat();
        //异域风情发起请求统计
        StatisticsUtils.statisticsFaceSecret(StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_FACE_SWAP + "_" +
                StatisticsConstant.STATISTIC_EVENT_VALUE_REPORT_GET_PIC + "_"
                + StatisticsConstant.STATISTIC_EVENT_VALUE_REQUEST);
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_RESULT_PAGE_REQUEST, StatisticsConstant.KEY_TREND_FUN,
                StatisticsConstant.MAIN_PAGE_VALUE_FACE_SWAP);
        SPDataManager.setAdOneTimeVip(false);
        FaceUtil.swapFace(pic, templateId, this, new FaceBaseCallback() {
            @Override
            public void onSuccess(Response response) {
                //异域风情请求成功统计
                StatisticsUtils.statisticsFaceSecret(StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_FACE_SWAP + "_" +
                        StatisticsConstant.STATISTIC_EVENT_VALUE_REPORT_GET_PIC_SUCCESS + "_"
                        + StatisticsConstant.STATISTIC_EVENT_VALUE_REQUEST + "_" + getStatisticsSuccessType());
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_RESULT_PAGE_REQUEST_SUCCEED, StatisticsConstant.KEY_TREND_FUN,
                        StatisticsConstant.MAIN_PAGE_VALUE_FACE_SWAP, StatisticsConstant.KEY_REQUEST_TIME, getStatisticsSuccessType());
                hideLoading();
                DLog.e(TAG, "requestSwap -> success");
                okhttp3.Response rawResponse = response.getRawResponse();
                if (rawResponse == null) {
                    return;
                }
                ResponseBody responseBody = rawResponse.body();
                if (responseBody == null) {
                    return;
                }
                new ParseBodyTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, responseBody);
            }

            @Override
            public void onError(Response response) {
                //异域风情请求失败统计
                StatisticsUtils.statisticsFaceSecret(StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_FACE_SWAP + "_" +
                        StatisticsConstant.STATISTIC_EVENT_VALUE_REPORT_GET_PIC_FAIL + "_"
                        + StatisticsConstant.STATISTIC_EVENT_VALUE_REQUEST + "_" + getStatisticsSuccessType());
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_RESULT_PAGE_REQUEST_FAILED, StatisticsConstant.KEY_TREND_FUN,
                        StatisticsConstant.MAIN_PAGE_VALUE_FACE_SWAP, StatisticsConstant.KEY_REQUEST_FAILED_REASON, response.message());
                hideLoading();
                DLog.e(TAG, "requestSwap -> onError");
                ToastUtil.showToast(R.string.exotic_fail_other_reason);
//                requestFailStat(response, throwable);
//                dismissProgressBar();
//                loadOriginalImage();
//                resetToPrevious();
//                showErrorMessage(response, throwable);
//                DLog.e(TAG, "onError: " + throwable.getMessage());
            }
        });
    }

    protected String getStatisticsSuccessType() {
        if (startRequest == 0) {
            startRequest = System.currentTimeMillis();
        }
        long durationSec = (System.currentTimeMillis() - startRequest) / TimeConstant.ONE_SEC;
        if (durationSec <= 4 && durationSec >= 0) {
            return STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_4;
        } else if (durationSec <= 6) {
            return STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_6;
        } else if (durationSec <= 10) {
            return STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_10;
        } else {
            return STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_ABOVE_10;
        }
    }

    class ParseBodyTask extends AsyncTask<ResponseBody, Void, String> {
        @Override
        protected String doInBackground(ResponseBody... responseBodies) {
            if (responseBodies == null || responseBodies.length < 1) {
                return null;
            }
            ResponseBody responseBody = responseBodies[0];
            try {
                String result = responseBody.string();
                if (TextUtils.isEmpty(result)) {
                    return null;
                }
                JSONObject jsonObject = new JSONObject(result);
                int code = jsonObject.optInt("code");
                if (code == 3) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast(R.string.concurrency_limit_tip);
                        }
                    });
                    return null;
                }
                if (!jsonObject.optBoolean("success")) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast(R.string.exotic_fail_other_reason);
                        }
                    });
                    return null;
                }
                JSONObject dataJson = jsonObject.optJSONObject("data");
                if (dataJson == null) {
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast(R.string.exotic_fail_other_reason);
                        }
                    });
                    return null;
                }
                String picBase64 = (String) dataJson.get("result");
                if (TextUtils.isEmpty(picBase64)) {
                    return null;
                }
                //统计
                requestSucceedStat(getTimeInterval(startRequest));
                DLog.i(TAG, "onSuccess: " + picBase64);
                //cache
                setSwapCache(mTemplateId, picBase64);
                return picBase64;
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String picBase64) {
            super.onPostExecute(picBase64);
            if (!TextUtils.isEmpty(picBase64)) {
                //显示到image view
                showSwapPic(picBase64);
            }
        }
    }

    @Override
    public Bitmap getSaveImg() {
        if (mSwapCache.containsKey(mTemplateId)) {
            final String base64 = mSwapCache.get(mTemplateId);
            if (!TextUtils.isEmpty(base64)) {
                return BitmapUtils.base64ToBitmap(base64);
            }
        } else {
            return ImageHelper.getBitmapFromPath(mImagePath);
        }
        return null;
    }

    private void showLoading() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.VISIBLE);
            mLoadingView.playAnimation();
            if (mActivity instanceof FaceLogicActivity) {
                ((FaceLogicActivity) mActivity).getEmptyView().setVisibility(View.VISIBLE);
            }
        }
    }

    private void hideLoading() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.GONE);
            mLoadingView.cancelAnimation();
            if (mActivity instanceof FaceLogicActivity) {
                ((FaceLogicActivity) mActivity).getEmptyView().setVisibility(View.GONE);
            }
        }
    }

    /**
     * 显示最终图片的同时，需要更换模糊背景，更换模糊背景genBackground，直接rx子线程执行。
     *
     * @param pic
     */
    private void showSwapPic(final String pic) {
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
//                ImageLoader.loadImageFromBase64(ComponentContext.getContext(), pic, mImageView);
                mImageView.setImageBitmap(BitmapUtils.base64ToBitmap(pic));
            }
        });
    }

    /**
     * 缓存结果
     * key 模板id
     * value 合成结果
     *
     * @param templateId 模板
     * @param pic        合成结果
     */
    private void setSwapCache(String templateId, String pic) {
        if (!mSwapCache.containsKey(templateId)) {
            DLog.i(TAG, "setSwapCache: 加入缓存");
            mSwapCache.put(templateId, pic);
        }
//        save.setEnabled(mSwapCache.size() > 0);
    }

    private String getMostPossibilityType(List<Double> percents) {
        double max = 0;
        int index = 0;
        for (int i = 0; i < percents.size(); i++) {
            double val = percents.get(i).doubleValue();
            if (val > max) {
                max = val;
                index = i;
            }
        }
        return getTypeByIndex(index);
    }

    private String getTypeByIndex(int index) {
        String ret = STATISTIC_EVENT_FUN_VALUE_OTHER;
        switch (index) {
            case 0:
                ret = STATISTIC_EVENT_FUN_VALUE_HISIPANIC;
                break;
            case 1:
                ret = STATISTIC_EVENT_FUN_VALUE_CAUCASIAN;
                break;
            case 2:
                ret = STATISTIC_EVENT_FUN_VALUE_BLACK;
                break;
            case 3:
                ret = STATISTIC_EVENT_FUN_VALUE_OTHER;
                break;
            case 4:
                ret = STATISTIC_EVENT_FUN_VALUE_MIDDLEEASTERN;
                break;
            case 5:
                ret = STATISTIC_EVENT_FUN_VALUE_ASIAN;
                break;
        }
        return ret;
    }

    private Double getPercentDouble(String percentStr) {
        double ret = 0;
        float percent = parse2Float(percentStr);
        // 雷达图中总分1
        ret = percent * 0.01f;
        return ret;
    }

    private float parse2Float(String percent) {
        float ret = 0;
        // 去掉末尾百分号
        String tmp = percent.trim().replace("%", "");
        tmp = tmp.trim();
        if (tmp == null || tmp.equals("")) return 0f;
        if (!TextUtils.isDigitsOnly(tmp)) {//还包含其他的字符
            if (Utils.hasInteger(tmp)) {//含有整数，才能提取Float
                Float onlyFloat = Utils.getOnlyFloat(tmp);
                if (onlyFloat == null) {//未提取到Float，是否只含有整数
                    Integer onlyInteger = Utils.getOnlyInteger(tmp);
                    if (onlyInteger == null) return 0f;
                    if (onlyInteger.intValue() > 100 || onlyInteger.intValue() < 0) return 0f;
                    return onlyInteger.intValue();
                }
                return onlyFloat.floatValue();
            } else {
                return 0f;
            }
        } else {
            ret = Float.parseFloat(tmp);
            return ret;
        }
    }

    @Override
    public int getReportTitleResId() {
        return R.string.report_title_exotic;
    }

    @Override
    public String getFeatureType() {
        return StatisticsConstant.STATISTIC_EVENT_FEATURE_VALUE_FEATURE_FACE_SWAP;
    }

    @Override
    public boolean needScrool() {
        return true;
    }

    @Override
    public void updateImage(String image) {

    }

    @Override
    public void onSubscribeSuccess() {

    }

    @Override
    public boolean titleBarWithoutBg() {
        return true;
    }

    public void destroy() {
        mActivity = null;
        OkGo.getInstance().cancelTag(this);
    }

}
